package com.xcode.socket.udp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 消息发送端
 * 
 * @author 肖蕾
 */
public class SocketUDPClient
{
	private DatagramSocket socket = null;
	private DatagramPacket packet = null;
	private byte[] def = new byte[1];
	private InetAddress address;
	private int port = -1;

	public SocketUDPClient()
	{
		try
		{
			socket = new DatagramSocket();
			packet = new DatagramPacket(def, def.length);
		} catch (Exception e)
		{
			throw new RuntimeException("SocketClient 初始化失败");
		}
	}

	public SocketUDPClient(String ip, int port)
	{
		try
		{
			socket = new DatagramSocket();
			packet = new DatagramPacket(def, def.length);
			address = InetAddress.getByName(ip);
			packet.setAddress(address);
			this.port = port;
			packet.setPort(this.port);
		} catch (UnknownHostException e)
		{
			throw new RuntimeException(
					"SocketClient(String ip,int port) 发送ip设置失败");
		} catch (Exception e)
		{
			throw new RuntimeException("SocketClient 初始化失败");
		}
	}


	/**
	 * 发送消息
	 * 
	 * @param data
	 *            发送的内容
	 * @param ip
	 *            发送的ip地址
	 * @param port
	 *            发送的端口号
	 */
	public void sendMessage(byte[] data)
	{
		try
		{
			packet.setData(data);
			packet.setLength(data.length);
			socket.send(packet);
		} catch (Exception e)
		{
			String errorMsg = "";
			if (address == null)
			{
				errorMsg += "\n发送的地址为空 setAddress(String ip)\n";
			}
			if (port == -1)
			{
				errorMsg += "发送的端口为空 setPort(int port)\n";
			}
			throw new RuntimeException(errorMsg);
		}
	}

	/**
	 * 设置发送的IP地址
	 * 
	 * @param ip
	 *            发送的ip地址
	 */
	public void setAddress(String ip)
	{
		try
		{
			address = InetAddress.getByName(ip);
			packet.setAddress(address);
		} catch (UnknownHostException e)
		{
			throw new RuntimeException("setAddress(String ip) 发送ip设置失败");
		}
	}

	/**
	 * 设置发送的端口
	 * 
	 * @param port
	 *            发送的端口
	 */
	public void setPort(int port)
	{
		this.port = port;
		packet.setPort(this.port);
	}

	/**
	 * 释放资源
	 */
	public void close()
	{
		if (socket != null)
		{
			socket.close();
		}
	}
}
